using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace My.IdlConverter.LoadManager
{
    class AddinLoader : ComponentLoader
    {
        public AddinLoader()
        {
        }

        public override void Save(UserComponent addin)
        {
            XmlDocument document = new XmlDocument();
            document.Load(ComponentPath);

            string xPath = String.Format("//Plugins/Plugin");
            XmlNodeList nodeList = document.SelectNodes(xPath);
            foreach (XmlNode nextNode in nodeList)
            {
                XmlNode friendlyNameNode = nextNode.SelectSingleNode("//FriendlyName");
                XmlNode pathNode = nextNode.SelectSingleNode("//Path");
                XmlNode descriptionNode = nextNode.SelectSingleNode("//Description");
                XmlNode loadBehaviorNode = nextNode.SelectSingleNode("//LoadBehavior");
                if (addin.Path.Trim().Equals(pathNode.InnerText.Trim()))
                {
                    friendlyNameNode.InnerText = addin.FriendlyName;
                    descriptionNode.InnerText = addin.Description;
                    loadBehaviorNode.InnerText = addin.LoadBehavior ? "1" : "0";
                    break;
                }
            }

            System.IO.File.SetAttributes(ComponentPath, System.IO.FileAttributes.Normal);
            document.Save(ComponentPath);
        }

        public override IList<UserComponent> Components
        {
            get
            {
                XmlDocument document = new XmlDocument();
                document.Load(ComponentPath);
                IList<UserComponent> addins = new List<UserComponent>();
                string xPath = String.Format("//Plugins/Plugin");
                XmlNodeList nodeList = document.SelectNodes(xPath);
                foreach (XmlNode nextNode in nodeList)
                {
                    XmlNode friendlyNameNode = nextNode.SelectSingleNode("//FriendlyName");
                    XmlNode pathNode = nextNode.SelectSingleNode("//Path");
                    XmlNode descriptionNode = nextNode.SelectSingleNode("//Description");
                    XmlNode loadBehaviorNode = nextNode.SelectSingleNode("//LoadBehavior");
                    UserComponent addin = new UserComponent();
                    addin.FriendlyName = friendlyNameNode.InnerText.Trim();
                    addin.Description = descriptionNode.InnerText.Trim();
                    addin.Path = pathNode.InnerText.Trim();
                    string loadBehavior = loadBehaviorNode.InnerText.Trim();
                    addin.LoadBehavior = (Convert.ToInt32(loadBehavior)==1) ? true : false;

                    addin.CfgFile = ComponentPath;
                    addin.Type = LoadManager.Config.TypeName;
                    addins.Add(addin);
                }
                return addins;
            }
        }
    }
}
